import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/28 21:16
 * @description
 */
public class Solution2 {
    public static void main(String[] args) {

    }

    public String rankTeams(String[] votes) {
        int n = votes.length, m = votes[0].length();
        if (n == 1) {
            return votes[0];
        }
        int[][] teamRank = new int[26][m + 1];
        for (int i = 0; i < 26; i++) {
            // 0位置作为id
            teamRank[i][0] = i;
        }
        for (String vote : votes) {
            for (int i = 0; i < vote.length(); i++) {
                teamRank[vote.charAt(i) - 'A'][i + 1]++;
            }
        }
        Arrays.sort(teamRank, (a, b) -> {
            for (int i = 1; i <= a.length; i++) {
                if (a[i] != b[i]) {
                    return b[i] - a[i];
                }
            }
            return a[0] - b[0];
        });
        StringBuffer sb = new StringBuffer();
        int cur = 0;
        for (int[] arr : teamRank) {
            sb.append((char) (arr[0] + 'A'));
            cur++;
            if (cur == n) {
                break;
            }
        }
        return sb.toString();
    }
}
